class TankGame {
    constructor() {
        this.canvas = document.getElementById('gameCanvas');
        this.ctx = this.canvas.getContext('2d');
        this.width = this.canvas.width;
        this.height = this.canvas.height;
        
        this.gridSize = 40;
        this.cols = this.width / this.gridSize;
        this.rows = this.height / this.gridSize;
        
        this.player = null;
        this.enemies = [];
        this.bullets = [];
        this.blocks = [];
        this.powerups = [];
        
        this.keys = {};
        this.score = 0;
        this.lives = 3;
        this.level = 1;
        
        this.gameRunning = false;
        this.lastTime = 0;
        
        this.initEventListeners();
    }
    
    initEventListeners() {
        document.addEventListener('keydown', (e) => {
            this.keys[e.key.toLowerCase()] = true;
        });
        
        document.addEventListener('keyup', (e) => {
            this.keys[e.key.toLowerCase()] = false;
        });
    }
    
    startGame(levelData = null) {
        this.reset();
        this.loadLevel(levelData || this.getDefaultLevel());
        this.gameRunning = true;
        this.gameLoop();
    }
    
    reset() {
        this.player = null;
        this.enemies = [];
        this.bullets = [];
        this.blocks = [];
        this.powerups = [];
        this.score = 0;
        this.updateUI();
    }
    
    getDefaultLevel() {
        return {
            blocks: [
                // 边界墙
                ...Array.from({length: this.cols}, (_, i) => ({x: i, y: 0, type: 'steel'})),
                ...Array.from({length: this.cols}, (_, i) => ({x: i, y: this.rows-1, type: 'steel'})),
                ...Array.from({length: this.rows-2}, (_, i) => ({x: 0, y: i+1, type: 'steel'})),
                ...Array.from({length: this.rows-2}, (_, i) => ({x: this.cols-1, y: i+1, type: 'steel'})),
                
                // 内部砖墙
                {x: 5, y: 5, type: 'brick'},
                {x: 6, y: 5, type: 'brick'},
                {x: 7, y: 5, type: 'brick'},
                {x: 8, y: 5, type: 'brick'},
                {x: 5, y: 6, type: 'brick'},
                {x: 8, y: 6, type: 'brick'},
                {x: 5, y: 7, type: 'brick'},
                {x: 8, y: 7, type: 'brick'},
                
                {x: 15, y: 8, type: 'brick'},
                {x: 16, y: 8, type: 'brick'},
                {x: 17, y: 8, type: 'brick'},
                
                {x: 10, y: 12, type: 'steel'},
                {x: 11, y: 12, type: 'steel'},
                
                // 基地
                {x: 9, y: 13, type: 'base'}
            ],
            player: {x: 10, y: 14},
            enemies: [
                {x: 2, y: 2},
                {x: 17, y: 2},
                {x: 10, y: 3}
            ]
        };
    }
    
    loadLevel(levelData) {
        this.blocks = levelData.blocks.map(b => ({
            x: b.x * this.gridSize,
            y: b.y * this.gridSize,
            type: b.type,
            health: b.type === 'brick' ? 1 : (b.type === 'steel' ? Infinity : 1)
        }));
        
        this.player = new Player(
            levelData.player.x * this.gridSize,
            levelData.player.y * this.gridSize,
            this.gridSize
        );
        
        this.enemies = levelData.enemies.map(e => new Enemy(
            e.x * this.gridSize,
            e.y * this.gridSize,
            this.gridSize
        ));
    }
    
    update(deltaTime) {
        if (!this.gameRunning) return;
        
        // 更新玩家
        if (this.player) {
            this.player.update(deltaTime, this.keys, this.blocks);
            
            // 玩家射击
            if (this.keys[' ']) {
                const bullet = this.player.shoot();
                if (bullet) this.bullets.push(bullet);
            }
        }
        
        // 更新敌人
        this.enemies.forEach(enemy => {
            enemy.update(deltaTime, this.blocks, this.player);
            if (Math.random() < 0.01) {
                const bullet = enemy.shoot();
                if (bullet) this.bullets.push(bullet);
            }
        });
        
        // 更新子弹
        this.bullets = this.bullets.filter(bullet => {
            bullet.update(deltaTime);
            
            // 检查边界
            if (bullet.x < 0 || bullet.x > this.width || 
                bullet.y < 0 || bullet.y > this.height) {
                return false;
            }
            
            // 检查碰撞
            return this.checkBulletCollisions(bullet);
        });
        
        // 检查游戏结束
        this.checkGameOver();
    }
    
    checkBulletCollisions(bullet) {
        // 检查与方块的碰撞
        for (let i = this.blocks.length - 1; i >= 0; i--) {
            const block = this.blocks[i];
            if (this.isColliding(bullet, block)) {
                if (block.type === 'brick') {
                    this.blocks.splice(i, 1);
                    this.score += 10;
                } else if (block.type === 'base') {
                    this.gameOver(false);
                    return false;
                }
                return false;
            }
        }
        
        // 检查与坦克的碰撞
        const target = bullet.isPlayer ? this.enemies : [this.player];
        for (let tank of target) {
            if (tank && this.isColliding(bullet, tank)) {
                if (bullet.isPlayer) {
                    this.enemies = this.enemies.filter(e => e !== tank);
                    this.score += 100;
                } else if (tank === this.player) {
                    this.lives--;
                    if (this.lives <= 0) {
                        this.gameOver(false);
                    } else {
                        this.respawnPlayer();
                    }
                }
                return false;
            }
        }
        
        return true;
    }
    
    isColliding(obj1, obj2) {
        return obj1.x < obj2.x + obj2.size &&
               obj1.x + obj1.size > obj2.x &&
               obj1.y < obj2.y + obj2.size &&
               obj1.y + obj1.size > obj2.y;
    }
    
    respawnPlayer() {
        // 简单重生逻辑
        this.player.x = 10 * this.gridSize;
        this.player.y = 14 * this.gridSize;
    }
    
    checkGameOver() {
        if (this.enemies.length === 0) {
            this.gameOver(true);
        }
    }
    
    gameOver(won) {
        this.gameRunning = false;
        if (won) {
            alert('恭喜通关！得分：' + this.score);
            this.saveScore();
        } else {
            alert('游戏结束！得分：' + this.score);
            this.saveScore();
        }
        showMenu();
    }
    
    saveScore() {
        const scores = JSON.parse(localStorage.getItem('tankScores') || '[]');
        scores.push({
            score: this.score,
            date: new Date().toLocaleDateString()
        });
        scores.sort((a, b) => b.score - a.score);
        scores.splice(10); // 只保留前10名
        localStorage.setItem('tankScores', JSON.stringify(scores));
    }
    
    render() {
        this.ctx.clearRect(0, 0, this.width, this.height);
        
        // 绘制网格
        this.drawGrid();
        
        // 绘制方块
        this.blocks.forEach(block => this.drawBlock(block));
        
        // 绘制道具
        this.powerups.forEach(powerup => this.drawPowerup(powerup));
        
        // 绘制坦克
        if (this.player) this.drawTank(this.player);
        this.enemies.forEach(enemy => this.drawTank(enemy));
        
        // 绘制子弹
        this.bullets.forEach(bullet => this.drawBullet(bullet));
    }
    
    drawGrid() {
        this.ctx.strokeStyle = '#2c3e50';
        this.ctx.lineWidth = 1;
        
        for (let x = 0; x <= this.width; x += this.gridSize) {
            this.ctx.beginPath();
            this.ctx.moveTo(x, 0);
            this.ctx.lineTo(x, this.height);
            this.ctx.stroke();
        }
        
        for (let y = 0; y <= this.height; y += this.gridSize) {
            this.ctx.beginPath();
            this.ctx.moveTo(0, y);
            this.ctx.lineTo(this.width, y);
            this.ctx.stroke();
        }
    }
    
    drawBlock(block) {
        this.ctx.fillStyle = {
            'brick': '#8B4513',
            'steel': '#708090',
            'water': '#4682B4',
            'forest': '#228B22',
            'base': '#FFD700'
        }[block.type] || '#808080';
        
        this.ctx.fillRect(block.x, block.y, block.size, block.size);
        
        // 添加边框
        this.ctx.strokeStyle = '#2c3e50';
        this.ctx.strokeRect(block.x, block.y, block.size, block.size);
    }
    
    drawTank(tank) {
        this.ctx.save();
        this.ctx.translate(tank.x + tank.size/2, tank.y + tank.size/2);
        this.ctx.rotate(tank.angle);
        
        // 坦克主体
        this.ctx.fillStyle = tank === this.player ? '#3498db' : '#e74c3c';
        this.ctx.fillRect(-tank.size/2, -tank.size/2, tank.size, tank.size);
        
        // 炮管
        this.ctx.fillStyle = '#2c3e50';
        this.ctx.fillRect(0, -tank.size/4, tank.size/2, tank.size/2);
        
        this.ctx.restore();
    }
    
    drawBullet(bullet) {
        this.ctx.fillStyle = bullet.isPlayer ? '#3498db' : '#e74c3c';
        this.ctx.beginPath();
        this.ctx.arc(bullet.x + bullet.size/2, bullet.y + bullet.size/2, 3, 0, Math.PI * 2);
        this.ctx.fill();
    }
    
    drawPowerup(powerup) {
        this.ctx.fillStyle = '#27ae60';
        this.ctx.fillRect(powerup.x, powerup.y, powerup.size, powerup.size);
        this.ctx.fillStyle = 'white';
        this.ctx.font = '20px Arial';
        this.ctx.textAlign = 'center';
        this.ctx.fillText('P', powerup.x + powerup.size/2, powerup.y + powerup.size/2 + 7);
    }
    
    updateUI() {
        document.getElementById('lives').textContent = this.lives;
        document.getElementById('score').textContent = this.score;
        document.getElementById('level').textContent = this.level;
    }
    
    gameLoop(currentTime = 0) {
        if (!this.gameRunning) return;
        
        const deltaTime = currentTime - this.lastTime;
        this.lastTime = currentTime;
        
        this.update(deltaTime);
        this.render();
        this.updateUI();
        
        requestAnimationFrame((time) => this.gameLoop(time));
    }
}

class Tank {
    constructor(x, y, size) {
        this.x = x;
        this.y = y;
        this.size = size;
        this.speed = 2;
        this.angle = 0;
        this.lastShot = 0;
        this.shotCooldown = 500;
    }
    
    update(deltaTime, keys, blocks) {
        // 基础移动逻辑由子类实现
    }
    
    shoot() {
        const now = Date.now();
        if (now - this.lastShot < this.shotCooldown) return null;
        
        this.lastShot = now;
        
        const bulletSize = 8;
        const bulletX = this.x + this.size/2 - bulletSize/2 + Math.cos(this.angle) * this.size/2;
        const bulletY = this.y + this.size/2 - bulletSize/2 + Math.sin(this.angle) * this.size/2;
        
        return new Bullet(bulletX, bulletY, bulletSize, this.angle, this instanceof Player);
    }
    
    canMoveTo(newX, newY, blocks) {
        // 检查边界
        if (newX < 0 || newX + this.size > 800 || newY < 0 || newY + this.size > 600) {
            return false;
        }
        
        // 检查与方块的碰撞
        for (let block of blocks) {
            if (newX < block.x + block.size &&
                newX + this.size > block.x &&
                newY < block.y + block.size &&
                newY + this.size > block.y) {
                return false;
            }
        }
        
        return true;
    }
}

class Player extends Tank {
    update(deltaTime, keys, blocks) {
        let newX = this.x;
        let newY = this.y;
        
        if (keys['w']) {
            newY -= this.speed;
            this.angle = -Math.PI/2;
        }
        if (keys['s']) {
            newY += this.speed;
            this.angle = Math.PI/2;
        }
        if (keys['a']) {
            newX -= this.speed;
            this.angle = Math.PI;
        }
        if (keys['d']) {
            newX += this.speed;
            this.angle = 0;
        }
        
        if (this.canMoveTo(newX, newY, blocks)) {
            this.x = newX;
            this.y = newY;
        }
    }
}

class Enemy extends Tank {
    constructor(x, y, size) {
        super(x, y, size);
        this.speed = 1;
        this.directionTimer = 0;
        this.directionInterval = 2000;
        this.currentDirection = Math.floor(Math.random() * 4);
    }
    
    update(deltaTime, blocks, player) {
        this.directionTimer += deltaTime;
        
        if (this.directionTimer > this.directionInterval) {
            this.currentDirection = Math.floor(Math.random() * 4);
            this.directionTimer = 0;
        }
        
        let newX = this.x;
        let newY = this.y;
        
        switch (this.currentDirection) {
            case 0: // 上
                newY -= this.speed;
                this.angle = -Math.PI/2;
                break;
            case 1: // 右
                newX += this.speed;
                this.angle = 0;
                break;
            case 2: // 下
                newY += this.speed;
                this.angle = Math.PI/2;
                break;
            case 3: // 左
                newX -= this.speed;
                this.angle = Math.PI;
                break;
        }
        
        if (!this.canMoveTo(newX, newY, blocks)) {
            this.currentDirection = Math.floor(Math.random() * 4);
        } else {
            this.x = newX;
            this.y = newY;
        }
        
        // 简单AI：朝向玩家
        if (player) {
            const dx = player.x - this.x;
            const dy = player.y - this.y;
            this.angle = Math.atan2(dy, dx);
        }
    }
}

class Bullet {
    constructor(x, y, size, angle, isPlayer) {
        this.x = x;
        this.y = y;
        this.size = size;
        this.speed = 5;
        this.angle = angle;
        this.isPlayer = isPlayer;
    }
    
    update(deltaTime) {
        this.x += Math.cos(this.angle) * this.speed;
        this.y += Math.sin(this.angle) * this.speed;
    }
}

// 全局游戏实例
let game = new TankGame();
